package com.woniuxy.dudugua.controller;

import com.woniuxy.dudugua.entity.Comment;
import com.woniuxy.dudugua.entity.Order;
import com.woniuxy.dudugua.entity.OrderInfo;
import com.woniuxy.dudugua.entity.User;
import com.woniuxy.dudugua.service.ProductScanService;
import com.woniuxy.dudugua.service.UserService;
import com.woniuxy.dudugua.util.Result;
import com.woniuxy.dudugua.util.kdniaoutil.KdniaoTrackQueryAPI;
import com.woniuxy.dudugua.util.view.GoodsListView;
import com.woniuxy.dudugua.util.view.OrderListView;
import org.apache.shiro.SecurityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("order")
public class UserOrderController {
    @Resource
    private UserService userService;
    @Resource
    private ProductScanService productScanService;
    @Resource
    private KdniaoTrackQueryAPI kdniaoTrackQueryAPI;
    @Resource
    private RedisTemplate redisTemplate;
    @GetMapping("selectAll")
    public Result selectAllOrder() throws Exception{
        //获取权限系统中的用户id
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user);
        System.out.println(user);
        int userId=user.getId();
        //查询该用户id下的所有订单
        List<Order> orders = userService.selectOrderById(userId);
        //封装前端所需要的对象
        List<OrderListView> orderList = new ArrayList<>();
        //循环order集合，一个order里面有多个orderinfo对象
        for(Order order:orders){
            //一个orderId对应一个orderListView，一个orderListView对应多个orderInfo对象
            OrderListView orderListView = new OrderListView();
            List<OrderInfo> orderInfos = order.getOrderInfos();
            orderListView.setOrderId(order.getId());
            orderListView.setState(order.getStatus());
            //转换时间格式
            Date addTime = order.getAddTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(addTime);
            orderListView.setTime(time);
            orderListView.setTotal(order.getTotal());
            int num=0;
            //遍历orderinfos，取出sku对象
            ArrayList<GoodsListView> goodsList = new ArrayList<>();
            for(OrderInfo orderInfo:orderInfos){
                num=num+orderInfo.getNumber();
                GoodsListView goodsListView = new GoodsListView();
                goodsListView.setOrderInfoId(orderInfo.getId());
                goodsListView.setAttr(orderInfo.getProductSku().getProperty());
                goodsListView.setImage(orderInfo.getProductSku().getUrl());
                goodsListView.setNumber(orderInfo.getNumber());
                goodsListView.setPrice(orderInfo.getProductSku().getPrice());
                goodsListView.setTitle(orderInfo.getProductName());
                goodsListView.setKuaidi(orderInfo.getCourierNumber());
                goodsList.add(goodsListView);
            }
            orderListView.setNum(num);
            //将GoodsListView对象集合放入orderlistView属性中
            orderListView.setGoodslist(goodsList);
            orderList.add(orderListView);
        }
        return new Result("200","success",null,orderList);
    }
    /**
     * 用户取消订单，传入一个orderid，改变order表的状态
     */
    @RequestMapping("cancel")
    public Result cancelOrder(int orderId) throws Exception{
        userService.cancelOrder(orderId);
        return new Result("200","success",null,null);
    }
    /**
     * 用户确认收货，改变订单表的状态
     */
    @RequestMapping("commit")
    public Result commitOrder(int orderId) throws Exception{
        userService.commitOrder(orderId);
        return new Result("200","success",null,null);
    }
    /**
     * 用户删除订单，传入一个orderId，删除该订单,同时删除订单详情表中的orderid
     */
    @RequestMapping("delete")
    public Result deleteOrder(int orderId) throws Exception{
        userService.deleteOrder(orderId);
        return new Result("200","success",null,null);
    }
    /**
     * 用户查询浏览历史
     */
    @GetMapping("selectScan")
    public Result selectScan()throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        int userId=user.getId();
        return new Result("200","success",null,productScanService.selectScan(userId));
    }
    /**
     * 用户支付，传入订单id，更新订单状态，更新user中的余额,redis存入一个key，key过期自动确认收货
     */
    @RequestMapping("pay")
    public Result payOrder(int orderId)throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getId();
        userService.payOrder(orderId,userId);
        String key="accept="+orderId;
        redisTemplate.opsForValue().set(key,"123",60*60*24*15, TimeUnit.SECONDS);
        return new Result("200","success",null,null);
    }
    /**
     * 前端传入一个orderinfo快递单号，然后再查询logistics中该快递单号的公司代号
     */
    @RequestMapping("wuliu")
    public Result getWuliu(String courierNumber)throws Exception{
        String companyCode = userService.getCompanyCode(courierNumber);
        String wuliuInfo = kdniaoTrackQueryAPI.getOrderTracesByJson(companyCode, courierNumber);
        return new Result("200","success",wuliuInfo,null);
    }
    @RequestMapping("wuliu1")
    public Result getWuliu1(String courierNumber)throws Exception{
        String address = userService.getAddress(courierNumber);
        return new Result("200","success",address,null);
    }
    /**
     * 传入一个orderinfoid，查询该商品详情的信息
     */
    @GetMapping("selectOrderInfo")
    public Result selectOrderInfo(Integer orderInfoId)throws Exception{
        return new Result("200","success",userService.selectOrderInfo(orderInfoId),null);
    }
    /**
     * 传入评论对象，增加一条评论
     */
    @PostMapping("comment")
    public Result insertComment(@RequestBody Comment comment)throws Exception{
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getId();
        comment.setUserId(userId);
        comment.setTime(new Date());
        Integer orderInfoId = comment.getOrderInfoId();
        //通过传过来的orderinfoid查询对应的商品属性id，然后再通过商品属性id查询商品id
        Integer productSkuId = userService.selectOrderInfo(orderInfoId).getProductSkuId();
        int productId = userService.selectProductId(productSkuId);
        comment.setProductId(productId);
        //新增评论，然后修改order表中的状态为6
        userService.insertComment(comment);
        return new Result("200","success",null,null);
    }
    /**
     * 传入一个orderid，取消订单，改变order中的status为5,并同时修改用户余额，返回优惠券
     */
    @GetMapping("returnMoney")
    public Result returnMoney(Integer orderId)throws Exception{
        userService.returnMoney(orderId);
        return new Result("200","success",null,null);
    }
    /**
     * 传入一个orderid，申请取消订单，新增一个returngoods
     */
    @GetMapping("wantReturn")
    public Result wantReturn(Integer orderId)throws Exception{
        userService.wantReturn(orderId);
        return new Result("200","success",null,null);
    }
    /**
     * 商家同意退货后，发送运单号，returnprocess添加一个运单号
     */
    @RequestMapping("addCourierNumber")
    public Result addCourierNumber(Integer returnId,String trackNumber)throws Exception{

        return new Result("200","success",null,null);
    }
}
